package com.lovergreen.mail.service;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Service;
import org.thymeleaf.TemplateEngine;
import org.thymeleaf.context.Context;

import javax.mail.MessagingException;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import java.util.Date;
import java.util.Locale;

@Service
public class EmailService {
    @Autowired
    private JavaMailSender mailSender;
    @Autowired private TemplateEngine templateEngine;

    public void sendRegisterConfirmationMail(
            final String recipientName,
            final String recipientLastName,
            final String recipientEmail,
            final String confirmKey,
            final Locale locale)
            throws MessagingException
    {
        StringBuilder sb = new StringBuilder();
        sb.append("http://localhost:8080/lovergreen/confirm/");
        sb.append(confirmKey);

        final Context ctx = new Context(locale);
        ctx.setVariable("firstname", recipientName);
        ctx.setVariable("lastname", recipientLastName);
        ctx.setVariable("email", recipientEmail);
        ctx.setVariable("confirmkey", sb.toString());
        ctx.setVariable("subscriptiondate", new Date());

        final MimeMessage mimeMessage = this.mailSender.createMimeMessage();
        final MimeMessageHelper message = new MimeMessageHelper(mimeMessage, "UTF-8");


        message.setSubject("EDuran.Net Registration Confirmation Message");
        message.setFrom(new InternetAddress("EDuran.Net <lovergreen@lovergreen.com>"));
        message.setTo(recipientEmail);

        final String htmlContent = this.templateEngine.process("register-confirmation.html", ctx);
        message.setText(htmlContent, true);

        this.mailSender.send(mimeMessage);

    }
}
